<?php
namespace App\Console\Commands\Elasticsearch;

use App\Models\Order;
use Illuminate\Console\Command;

class SyncOrders extends Command
{
    protected $signature = 'es:sync-data {index}';

    protected $description = '将数据同步到 Elasticsearch';
    protected $es;
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // 获取 Elasticsearch 对象
        $this->es = app('es');
        $index = $this->argument('index');
        switch ($index){
            case 'orders':
                $this->syncOrders($this->es);
                break;
            case 'products':
                $this->syncProducts($this->es);
                break;
            default :
                $this->info('未知的索引类型');
                break;
        }
        $this->info('同步完成');
    }

    public function syncOrders($es){
        Order::with(['goods'])
        // 使用 chunkById 避免一次性加载过多数据
        ->chunkById(100, function ($orders) use ($es) {
            $this->info(sprintf('正在同步 ID 范围为 %s 至 %s 的订单', $orders->first()->id, $orders->last()->id));
            // 初始化请求体
            $req = ['body' => []];
            // 遍历订单
            foreach ($orders as $order) {
                $data = $order->toESArray();
                $req['body'][] = [
                    'index' => [
                        '_index' => 'orders',
                        '_id'    => $data['id'],
                    ],
                ];
                $req['body'][] = $data;
            }
            try {
                // 使用 bulk 方法批量创建
                $es->bulk($req);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        });
    }
}
